package com.laikan.reader.bookfriend.fragment.impl;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;

import com.google.gson.Gson;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.adapter.BaseListAdapter;
import com.laikan.reader.bookfriend.adapter.impl.AttentionAdapter;
import com.laikan.reader.bookfriend.entity.AttentionBean;
import com.laikan.reader.bookfriend.entity.ItemAttentionBean;
import com.laikan.reader.bookfriend.entity.PageAttentionBean;
import com.laikan.reader.bookfriend.fragment.BaseListFragment;
import com.laikan.reader.bookfriend.requester.AutherRequester;
import com.laikan.reader.bookfriend.requester.SimpleRequestListener;
import com.laikan.reader.bookfriend.utils.Constant;
import com.laikan.reader.bookfriend.utils.ImageUtils;
import com.laikan.reader.core.LaikanApplication;
import com.socks.library.KLog;

import java.util.List;

import thirdparty.swipemenulistview.SwipeMenu;
import thirdparty.swipemenulistview.SwipeMenuCreator;
import thirdparty.swipemenulistview.SwipeMenuItem;
import thirdparty.swipemenulistview.SwipeMenuListView;

/**
 * Created by lingyt on 2016/11/17.
 * 关注页
 */
public class AttentionFragment extends BaseListFragment{

    public SwipeMenuListView mRecyclerView;
    public AttentionAdapter mAdapter;
    private String autherId;

    public void setAutherId(String autherId) {
        this.autherId = autherId;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mBundle != null) {
           String userId = mBundle.getString(Constant.USER_ID,"");
           setAutherId(userId);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_list_defalult2;
    }

    @Override
    public void initListViewAndAdapter() {
        mRecyclerView = (SwipeMenuListView) mBodyView.findViewById(R.id.recyclerview);

        if (mAdapter == null) {
            mAdapter= getListAdapter();
            mRecyclerView.setAdapter(mAdapter);
        }else{
            mAdapter.notifyDataSetChanged();;
        }

        mRecyclerView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE){
                    if (view.getLastVisiblePosition() == (view.getCount()-1)){

                        if (hasMore){
                            KLog.w(args,"有跟多数据，发起加载更多的数据请求");
                            sendLoadMoreRequest();
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });


        SwipeMenuCreator creator = new SwipeMenuCreator(){
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(LaikanApplication.getContext());
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(ImageUtils.dip2px(80));
                // set a icon
                deleteItem.setTitle("取消关注");
                deleteItem.setTitleColor(Color.parseColor("#ffffff"));
                deleteItem.setTitleSize(17);
                // add to menu    将创建的菜单项添加进菜单中
                menu.addMenuItem(deleteItem);
            }
        };

        mRecyclerView.setMenuCreator(creator);
        mRecyclerView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
                switch (index){
                    case 0:
                        // TODO: 2016/11/7 取消关注
                        KLog.w(args,"右边按钮被点击");
                        onRightMenuClick(position);
                        break;
                }
                return false;
            }
        });
        mRecyclerView.addFooterView(mAdapter.getMoreHolder().getRootView());


    }

    private AttentionAdapter getListAdapter() {
        return new AttentionAdapter();
    }

    private void onRightMenuClick(int position) {
        ItemAttentionBean bean = (ItemAttentionBean) mAdapter.getData().get(position);
        toDelPosition = position;//记录点击的位置
        sendDelAttentionRequest(bean.attentionId);
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onClickEvent(View view) {

    }

    @Override
    protected BaseListAdapter getAdapter() {
        return null;
    }

    @Override
    protected void loadData(int pageNo) {
        KLog.w(args,"load Data:开始加载第  "+pageNo+" 页数据");
        String authorId = getAuthorId();
        AutherRequester.requestAttentionList(pageNo,authorId,mCallback);
    }

    /*private SimpleCallback<PageAttentionBean> mCallback = new SimpleCallback<PageAttentionBean>(this) {
        @Override
        public void onSuccess(HttpResponse httpResponse, PageAttentionBean pageAttentionBean) {
            setFragmentData(pageAttentionBean);

        }

        @Override
        public void onError(VolleyErrorHandler errorHandler) {
            onRequestDataError();
        }


    };*/

    private SimpleRequestListener mCallback = new SimpleRequestListener(this){

        @Override
        public void onSuccess(HttpResponse httpResponse) {
            PageAttentionBean pageAttentionBean = mGson.fromJson(httpResponse.responseContent,PageAttentionBean.class);
            setFragmentData(pageAttentionBean);
        }

        @Override
        public void onError(VolleyErrorHandler errorHandler) {
            onRequestDataError();
        }
    };

    private String getAuthorId() {
//      test  return "6314266";
        return this.autherId;
    }

    @Override
    protected void onRequestDataSuccess(List list) {
        isLoadOnce = true;
        mAdapter.addData(list);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void refreshFragmentData() {
        PageAttentionBean bean = (PageAttentionBean) getFragmentData();
        mState = checkData(bean.data.list);
        KLog.w(args,"mState == "+ mState +"isLoadOnce =="+isLoadOnce);
        showData(bean.data.list);
    }

    @Override
    public void changeAdapterState(boolean hasMore) {
        mAdapter.setHasMoreState(hasMore);
    }


    @Override
    protected void onRequestDataEmpty() {
        KLog.w(args,"isLoadOnce = "+isLoadOnce+"----"+"onRequestDataEmpty");
        if (!isLoadOnce) {
            mTipinfoLayout.setEmptyData(R.string.test, R.drawable.book_list_null);
        } else {
            ToastMgr.showShortToast("服务器返回数据为空");
        }
    }




    @Override
    public void hideProgress() {
        super.hideProgress();
    }

    public static final int FLAG_ADD_ATTENTION = 1;
    public static final int FLAG_DEL_ATTENTION = 2;
    public static final int FLAG_ATTENTION_NONE = -1;
    public static int currFlag = 0;
    public int toDelPosition = -1;

    private void sendDelAttentionRequest(String objectId) {
        currFlag = FLAG_DEL_ATTENTION;
        AutherRequester.requestDelAttention(objectId,mHandler);
    }

    public RequestListener mHandler = new RequestListener() {
        @Override
        public void onPreExecute() {
            showDialog();
        }

        @Override
        public void onSuccess(HttpResponse httpResponse) {
            Gson gson = new Gson();
            AttentionBean bean = gson.fromJson(httpResponse.responseContent,AttentionBean.class);
            if (currFlag == FLAG_DEL_ATTENTION){
                onDelAttentionSuccess(bean);
            }
        }

        @Override
        public void onError(VolleyErrorHandler errorHandler) {
            if (currFlag == FLAG_DEL_ATTENTION){
                onDelAttentionError();
            }
        }

        @Override
        public void onFinish() {
            onAttentionFinish();
            dismissDialog();
        }
    };

    private void onDelAttentionSuccess(AttentionBean bean) {
        if (bean!=null && bean.result.equals("1")){
            if (mAdapter != null && toDelPosition!=-1) {
                mAdapter.delete(toDelPosition);
                mAdapter.notifyDataSetChanged();
                ToastMgr.showShortToast("取消成功： "+toDelPosition);
            }
        }else{
            onDelAttentionError();
        }
    }


    private void onDelAttentionError() {
        ToastMgr.showShortToast("取消失败");
    }

    private void onAttentionFinish() {
        toDelPosition =-1;
        currFlag = FLAG_ATTENTION_NONE;
    }






}
